package httpclient;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BasicHttpClient {

    public String get(String url, Map<String, String> params, Map<String, String> headers) {
        String response = "";
        List<Header> kvHeaders = new ArrayList<>();
        List<NameValuePair> kvParams = new ArrayList<>();

        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                kvParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                kvHeaders.add(new BasicHeader(entry.getKey(), entry.getValue()));
            }
        }

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpUriRequest request = RequestBuilder.get()
                    .setUri(url)
                    .addParameters(kvParams.toArray(new NameValuePair[kvParams.size()]))
                    .build();
            request.setHeaders(kvHeaders.toArray(new Header[kvHeaders.size()]));

            ResponseHandler<String> responseHandler = r -> {
                int status = r.getStatusLine().getStatusCode();
                if (status == 200) {
                    HttpEntity entity = r.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    return "service error";
                }
            };
            response = httpclient.execute(request, responseHandler);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}